package servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(urlPatterns = "/uploadtest")
public class uploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {// 1.创建上传文件的对象
            SmartUpload smartUpload = new SmartUpload();
            PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(this,req,resp,null,false,1024,true);
            smartUpload.initialize(pageContext);// 2.初始化上传的操作
            smartUpload.setCharset("utf-8");// 2.1 设置编码
            smartUpload.upload();// 3.上传
            File file = smartUpload.getFiles().getFile(0);// 4.获取文件信息
            String fileName = file.getFileName();
            //String contentType = file.getContentType();// 获取文件类型
            // 4.1 获取文本信息,请求的所有数据都放在SmartUpload自己定义的request中
            String text = smartUpload.getRequest().getParameter("text");
            System.out.println("随笔="+text);
            String uploadPath = "/uploadfiles/"+fileName;// 5.指定上传的路径
            // 6.保存到指定位置，参数2：当前文件存储到虚拟路径上面
            file.saveAs(uploadPath,File.SAVEAS_VIRTUAL);
            req.setAttribute("filename",fileName);
            req.getRequestDispatcher("success.jsp").forward(req,resp);// 7.跳转指定路径
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

    }
}
